/**
 *
 */
package com.naiterui.ehp.bs.doctor.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.naiterui.common.repository.page.CustomizedPageConvertor;
import com.naiterui.common.repository.page.PageParamVO;
import com.naiterui.common.repository.page.PageVO;
import com.naiterui.ehp.bp.bo.im.SessionDetailBO;
import com.naiterui.ehp.bp.bo.im.SessionParamBO;
import com.naiterui.ehp.bp.bo.patient.PatientInquirerBO;
import com.naiterui.ehp.bp.domain.ConsultSession;
import com.naiterui.ehp.bp.domain.DoctorCharge;
import com.naiterui.ehp.bp.domain.DrChargeConfig;
import com.naiterui.ehp.bp.domain.DrMessageConsultCharge;
import com.naiterui.ehp.bp.domain.DrMessageConsultChargePK;
import com.naiterui.ehp.bp.domain.DrMessageConsultOrder;
import com.naiterui.ehp.bp.domain.DrPatientGroupDetail;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.date.DateUtil;
import com.naiterui.ehp.bp.utils.lang.StringUtil;
import com.naiterui.ehp.bs.doctor.dao.IConsultSessionDao;
import com.naiterui.ehp.bs.doctor.dao.IDrMessageConsultChargeDao;
import com.naiterui.ehp.bs.doctor.dao.IDrMessageConsultOrderDao;
import com.naiterui.ehp.bs.doctor.dao.IDrPatientGroupDetailDao;
import com.naiterui.ehp.bs.doctor.dao.IPatientPersonDoctorDao;
import com.naiterui.ehp.bs.doctor.exception.ExceptionCodes;
import com.naiterui.ehp.bs.doctor.fegin.ImFeginClient;
import com.naiterui.ehp.bs.doctor.fegin.PatientFeignClient;
import com.naiterui.ehp.bs.doctor.repository.IDoctorChargeRepository;
import com.naiterui.ehp.bs.doctor.repository.IDrMessageConsultChargeRepository;
import com.naiterui.ehp.bs.doctor.service.IDrMessageConsultChargeService;
import com.naiterui.ehp.bs.doctor.service.IPatientGroupService;
import com.naiterui.ehp.bs.doctor.service.IPatientService;
import com.naiterui.ehp.bs.doctor.utils.PatientUtil;
import com.naiterui.ehp.bs.doctor.vo.ConsultChargePatientGroupDetailVO;
import com.naiterui.ehp.bs.doctor.vo.ConsultOrderListVO;
import com.naiterui.ehp.bs.doctor.vo.ConsultOrderVO;
import com.naiterui.ehp.bs.doctor.vo.ConsultSessionParamVO;
import com.naiterui.ehp.bs.doctor.vo.ConsultSessionVO;
import com.naiterui.ehp.bs.doctor.vo.PatientGroupVo;
import com.naiterui.ehp.bs.doctor.vo.PatientMessageChargeVO;
import com.naiterui.ehp.bs.doctor.vo.PatientVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 医生图文咨询收费业务层
 *
 * @author guoyongxiang
 * @since 2.7.0
 */
@Service
@RequiredArgsConstructor
public class AdDrMessageConsultChargeServiceImpl implements IDrMessageConsultChargeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdDrMessageConsultChargeServiceImpl.class);

    /**
     * 全选
     */
    private static final Integer SELECTED_ALL = 1;
    /**
     * 字符串列表分隔符
     */
    private static final String SPLIT_STR = ",";

    /**
     * 未分组ID
     */
    private static final Long UNGROUPED_ID = 0L;
    /**
     * 未分组名称
     */
    private static final String UNGROUPED_NAME = "未分组患者";

    private final ImFeginClient imFeginClient;
    private final IPatientService patientService;
    private final IPatientGroupService patientGroupService;
    private final IPatientPersonDoctorDao patientPersonDoctorDao;
    private final IDrPatientGroupDetailDao drPatientGroupDetailDao;
    private final IDrMessageConsultChargeDao drMessageConsultChargeDao;
    private final IConsultSessionDao consultSessionDao;
    private final IDrMessageConsultOrderDao drMessageConsultOrderDao;
    private final IDrMessageConsultChargeRepository drMessageConsultChargeRepository;
    private final IDoctorChargeRepository doctorChargeRepository;
    private final PatientFeignClient patientFeignClient;
    private final EntityManager entityManager;

    @Override
    public Integer getChargeById(Long doctorId, Long patientId) {
        // return this.drMessageConsultChargeDao.getChargeById(doctorId, patientId);
        DoctorCharge doctorCharge = doctorChargeRepository.findFirstByDoctorIdAndChargeType(doctorId, DrChargeConfig.TYPE_MESSAGE);
        return Optional.ofNullable(doctorCharge).map(DoctorCharge::getCharge).orElse(0);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveCharge(Long doctorId, Integer charge, Integer selectedAll, String groupIdStr, String patientIdStr)
            throws BusinessException {

        // 全选免费直接批量删除
        if (charge < 1 && SELECTED_ALL.equals(selectedAll)) {
            this.deleteChargeAll(doctorId);
        } else {

            // 获取选中患者列表
            Set<Long> patientIds = this.getSelectedPatientIds(doctorId, selectedAll, groupIdStr, patientIdStr);

            // 设置免费
            if (charge < 1) {
                this.deleteCharge(doctorId, patientIds);
            } else {
                this.updateCharge(doctorId, charge, patientIds);
            }
        }

    }

    /**
     * 获取选中的患者列表
     * DrMessageConsultChargeServiceImpl.getSelectedPatientIds()
     *
     * @param doctorId
     * @param selectedAll
     * @param groupIdStr
     * @param patientIdStr
     *
     * @return
     *
     * @throws BusinessException
     * @Author guoyongxiang
     * @Date 2017年4月1日
     * @since 2.7.0
     */
    private Set<Long> getSelectedPatientIds(Long doctorId, Integer selectedAll, String groupIdStr, String patientIdStr)
            throws BusinessException {

        Set<Long> patientIdSet = new HashSet<>();

        // 全选查询医生所有患者进行设置
        if (SELECTED_ALL.equals(selectedAll)) {

            // 查询医生所有的患者列表
            List<Long> patientIds = this.patientPersonDoctorDao.getPatientIdsByDoctorId(doctorId);
            patientIdSet.addAll(patientIds);

        } else {

            if (!StringUtils.isBlank(groupIdStr) && groupIdStr.length() > 0) {
                List<Long> groupIds = StringUtil.convertLongStr2List(groupIdStr, ",");
                // 全选了某个分组
                List<Long> patientIds = this.getPatientIdListByGroupIds(groupIds, doctorId);

                // 包含未分组的患者
                if (groupIds.contains(UNGROUPED_ID)) {
                    List<Long> ungroupedPatientIds = this.getUngroupedPatientIds(doctorId);
                    patientIds.addAll(ungroupedPatientIds);
                }

                patientIdSet.addAll(patientIds);
            }

            if (!StringUtils.isBlank(patientIdStr) && patientIdStr.length() > 0) {
                // 单独选择的患者
                List<Long> patientIds = StringUtil.convertLongStr2List(patientIdStr, SPLIT_STR);
                patientIdSet.addAll(patientIds);
            }
        }

        if (patientIdSet.size() < 1) {
            LOGGER.warn("未选择有效患者doctorId {}, selectedAll {}, groupIdStr {}, patientIdStr {}", doctorId, selectedAll, groupIdStr, patientIdStr);
            throw new BusinessException(ExceptionCodes.PARAM_ERROR, "未选择有效患者");
        }

        return patientIdSet;
    }

    /**
     * 删除患者收费设置
     * DrMessageConsultChargeServiceImpl.deleteChargeAll()
     *
     * @param doctorId
     *
     * @throws BusinessException
     * @Author guoyongxiang
     * @Date 2017年4月1日
     * @since 2.7.0
     */
    private void deleteChargeAll(Long doctorId) {
        this.drMessageConsultChargeDao.deleteChareByDoctorId(doctorId);
    }

    /**
     * 删除指定患者收费设置
     * DrMessageConsultChargeServiceImpl.deleteCharge()
     *
     * @param doctorId
     * @param patientIds
     *
     * @Author guoyongxiang
     * @Date 2017年4月1日
     * @since 2.7.0
     */
    private void deleteCharge(Long doctorId, Set<Long> patientIds) {
        this.drMessageConsultChargeDao.deleteChareByDoctorId(doctorId, patientIds);
    }

    /**
     * 更新患者收费设置
     * DrMessageConsultChargeServiceImpl.updateCharge()
     *
     * @param doctorId
     * @param charge
     * @param patientIds
     *
     * @Author guoyongxiang
     * @Date 2017年4月1日
     * @since 2.7.0
     */
    private void updateCharge(Long doctorId, Integer charge, Set<Long> patientIds) {

        Set<PatientMessageChargeVO> chargeVOSet = new HashSet<>();

        // 转换患者列表为费用设置VO列表
        this.convertChargeSet(chargeVOSet, charge, patientIds);

        // 已有记录
        List<DrMessageConsultCharge> oldData = this.drMessageConsultChargeRepository.findByDoctorIdAndPatientIdIn(doctorId, patientIds);
        Map<String, DrMessageConsultCharge> map = new HashMap<>();
        if (CollectionUtil.isNotEmpty(oldData)) {
            for (DrMessageConsultCharge consultCharge : oldData) {
                map.put(consultCharge.getChargePK().getDoctorId() + "-" + consultCharge.getChargePK().getPatientId(), consultCharge);
            }
        }

        if (CollectionUtil.isNotEmpty(chargeVOSet)) {
            List<DrMessageConsultCharge> chargeList = chargeVOSet.stream().map(vo -> {
                DrMessageConsultCharge messageConsultCharge = map.get(doctorId + "-" + vo.getPatientId());
                if (null == messageConsultCharge) {
                    messageConsultCharge = new DrMessageConsultCharge();
                    DrMessageConsultChargePK chargePK = new DrMessageConsultChargePK();
                    chargePK.setDoctorId(doctorId);
                    chargePK.setPatientId(vo.getPatientId());
                    messageConsultCharge.setChargePK(chargePK);
                }
                messageConsultCharge.setCharge(vo.getCharge());
                messageConsultCharge.setCreatedAt(new Date());
                messageConsultCharge.setCreatedBy("doctorSystem");
                return messageConsultCharge;
            }).collect(Collectors.toList());
            this.drMessageConsultChargeRepository.save(chargeList);
        }

        // 批量保存收费设置
        // drMessageConsultChargeDao.saveChargeByDoctorId(doctorId, chargeVOSet);
    }

    /**
     * 将患者ID列表转换成收费患者列表
     * DrMessageConsultChargeServiceImpl.convertChargeSet()
     *
     * @param chargeVOSet
     * @param charge
     * @param patientIds
     *
     * @Author guoyongxiang
     * @Date 2017年4月1日
     * @since 2.7.0
     */
    private void convertChargeSet(Set<PatientMessageChargeVO> chargeVOSet, Integer charge, Set<Long> patientIds) {
        for (Long patientId : patientIds) {
            chargeVOSet.add(new PatientMessageChargeVO(patientId, charge));
        }
    }

    /**
     * 根据分组ID列表获取患者ID列表
     * DrMessageConsultChargeServiceImpl.getPatientIdListByGroupIds()
     *
     * @param groupIds
     * @param doctorId
     *
     * @return
     *
     * @Author guoyongxiang
     * @Date 2017年4月2日
     * @since 2.7.0
     */
    private List<Long> getPatientIdListByGroupIds(List<Long> groupIds, Long doctorId) {
        List<DrPatientGroupDetail> groupPatients = this.drPatientGroupDetailDao.getDetailByGroupIds(groupIds, doctorId);

        List<Long> patientIds = new ArrayList<>();
        for (DrPatientGroupDetail groupPatient : groupPatients) {
            Long patientId = groupPatient.getPatientId();

            if (!patientIds.contains(patientId)) {
                patientIds.add(patientId);
            }
        }
        return patientIds;
    }

    @Override
    public List<PatientGroupVo> getPatientGroups(Long doctorId) {
        // 查询患者分组列表
        List<PatientGroupVo> group = this.patientGroupService.findPatientGroupByDoctorId(doctorId);

        // 增加未分组
        List<Long> ungroupedPatientIds = this.getUngroupedPatientIds(doctorId);
        group.add(new PatientGroupVo(UNGROUPED_ID, UNGROUPED_NAME, (long) ungroupedPatientIds.size()));

        // 过滤空分组
        List<PatientGroupVo> patientGroup = new ArrayList<>();
        for (PatientGroupVo vo : group) {
            if (vo.getGroupCount() > 0) {
                patientGroup.add(vo);
            }
        }

        return patientGroup;
    }

    /**
     * 根据医生id获取为分组患者信息
     * DrMessageConsultChargeServiceImpl.getUngroupedPatientIds()
     *
     * @param doctorId
     *
     * @return
     *
     * @Author guoyongxiang
     * @Date 2017年4月2日
     * @since 2.7.0
     */
    private List<Long> getUngroupedPatientIds(Long doctorId) {

        // 查询已分组患者列表
        List<DrPatientGroupDetail> groupPatientList = this.drPatientGroupDetailDao.getDetailByDoctorId(doctorId);
        Map<Long, DrPatientGroupDetail> patientIdMap = groupPatientList.stream()
                                                                       .collect(Collectors.toMap(DrPatientGroupDetail::getPatientId,
                                                                                                 groupPatient -> groupPatient, (a, b) -> b));

        // 查询医生所有患者列表
        List<Long> allPatientIds = this.patientPersonDoctorDao.getPatientIdsByDoctorId(doctorId);

        // 排除未分组用户
        List<Long> ungroupedPatientIds = new ArrayList<>();
        if (allPatientIds.size() != patientIdMap.size()) {
            ungroupedPatientIds = allPatientIds.stream().filter(patientId -> !patientIdMap.containsKey(patientId)).collect(Collectors.toList());
        }

        return ungroupedPatientIds;
    }

    @Override
    public List<ConsultChargePatientGroupDetailVO> getPatientsByGroupId(Long groupId, Long doctorId) throws Exception {
        // 根据分组ID查询组内患者
        Set<Long> patientIdSet = new HashSet<>();

        if (UNGROUPED_ID.equals(groupId)) {
            // 未分组
            List<Long> ungroupedPatientIds = this.getUngroupedPatientIds(doctorId);
            patientIdSet.addAll(ungroupedPatientIds);
        } else {
            // 已分组
            List<Long> groupPatientIds = this.drPatientGroupDetailDao.getPatientIdsByGroupId(groupId, doctorId);
            patientIdSet.addAll(groupPatientIds);
        }

        // 获取患者姓名信息
        List<Long> patientIds = new ArrayList<>(patientIdSet);
        List<PatientVo> patientVOList = this.patientService.getPatientsByDoctorId(doctorId, patientIds);

        // 查询收费价格
        Map<Long, Integer> chargeMap = this.drMessageConsultChargeDao.getChargeListByDoctorId(doctorId, patientIds);

        // 组装收费价格
        List<ConsultChargePatientGroupDetailVO> chargeList = new ArrayList<>();
        for (PatientVo patient : patientVOList) {

            Long patientId = patient.getId();

            // 患者姓名
            String name = patient.getName();
            if (!StringUtils.isBlank(patient.getRemarkName())) {
                name = patient.getRemarkName();
            }

            // 收费金额
            Integer charge = Optional.ofNullable(chargeMap.get(patientId)).orElse(0);
            chargeList.add(new ConsultChargePatientGroupDetailVO(patientId, name, patient.getPatientIcon(), patient.getAge(), patient.getGender(),
                                                                 charge));
        }

        return chargeList;
    }

    @Override
    public PageVO<ConsultSessionVO> consultSessionList(ConsultSessionParamVO paramVO, PageParamVO pageParamVO) throws BusinessException {

        Date gtTime = DateUtil.parseStrToCustomPatternDate(paramVO.getTime() + "01日00时00分00秒", "yyyy年MM月dd日HH时mm分ss秒");
        Date ltTime = DateUtil.addMonth(gtTime, 1);
        if (ltTime == null || gtTime == null) {
            LOGGER.error("consultSessionList param ERROR ; paramVO={}", paramVO);
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        PageVO<SessionDetailBO> sessionDetailPage = this.imFeginClient.sessionList(SessionParamBO
                                                                                           .builder()
                                                                                           .beginGt(gtTime.getTime())
                                                                                           .beginLt(ltTime.getTime())
                                                                                           .doctorId(paramVO.getDoctorId())
                                                                                           .feeType(paramVO.getFee())
                                                                                           .pageNo(pageParamVO.getPage())
                                                                                           .pageSize(pageParamVO.getNum())
                                                                                           .build());
        List<SessionDetailBO> sessionDetailList = sessionDetailPage.getResult();
        Set<Long> patientIdSet = sessionDetailList.stream().map(SessionDetailBO::getPatientId).collect(Collectors.toSet());
        List<PatientVo> patientVoList = this.patientService.findPatientByPatientId(paramVO.getDoctorId(), StringUtil.convertCollection(patientIdSet));
        Map<Long, PatientVo> patientVoMap = patientVoList.stream().collect(Collectors.toMap(PatientVo::getId, o -> o));

        List<ConsultSession> consultSessions = this.consultSessionDao.getConsultSession(paramVO.getDoctorId(), gtTime, ltTime);
        Set<String> chargeSessionIdSet = consultSessions.stream().map(ConsultSession::getSessionId).collect(Collectors.toSet());
        List<DrMessageConsultOrder> chargeOrderList = this.drMessageConsultOrderDao.findByCondition(chargeSessionIdSet);
        Integer sumCharge = chargeOrderList.stream().map(DrMessageConsultOrder::getPrice).reduce(0, Integer::sum);
        Map<String, DrMessageConsultOrder> chargeOrderMap = chargeOrderList.stream()
                                                                           .collect(Collectors.toMap(DrMessageConsultOrder::getSessionId, o -> o));
        List<ConsultSessionVO> resultList = sessionDetailList.stream().map(sessionDetail -> {
            PatientVo patientVo = patientVoMap.getOrDefault(sessionDetail.getPatientId(), new PatientVo());
            DrMessageConsultOrder consultOrder = chargeOrderMap.getOrDefault(sessionDetail.getSessionId(), new DrMessageConsultOrder());
            int consultStatus = sessionDetail.getEndTime() == null || sessionDetail.getEndTime() <= 0 ? ConsultSessionVO.CONSULT_STATUS_DURING :
                    ConsultSessionVO.CONSULT_STATUS_FINISH;
            return ConsultSessionVO
                    .builder()
                    .price(consultOrder.getPrice() == null ? 0 : consultOrder.getPrice())
                    .patientName(StringUtils.trimToEmpty(patientVo.getAbcName()))
                    .gender(PatientUtil.getGenderName(patientVo.getGender()))
                    .desc(sessionDetail.getFirstContent())
                    .containRecord(sessionDetail.getContainRecord())
                    .containRecom(sessionDetail.getContainRecom())
                    .consultTime(new Date(sessionDetail.getBeginTime()))
                    //TODO 支付状态常量在哪?
                    .consultStatus(consultOrder.getPayStatus() != null && consultOrder.getPayStatus() == 6 ?
                                           ConsultSessionVO.CONSULT_STATUS_REFUND : consultStatus)
                    .avatar(StringUtils.trimToEmpty(patientVo.getPatientIcon()))
                    .age(patientVo.getAge() + "岁")
                    .build();
        }).collect(Collectors.toList());
        return PageVO.newBuilder()
                     .pageSize(sessionDetailPage.getPageSize())
                     .pageNo(sessionDetailPage.getPageNo())
                     .totalCount(sessionDetailPage.getTotalCount())
                     .result(resultList)
                     //临时处理方案，此字段作为：月累计诊费字段使用
                     .orderBy(new BigDecimal(sumCharge).movePointLeft(2).stripTrailingZeros().toPlainString())
                     .build();
    }

    /**
     * 诊疗收入
     * @param paramVO
     * @param pageParamVO
     * @return
     */
    @Override
    public ConsultOrderListVO consultIncome(ConsultSessionParamVO paramVO, PageParamVO pageParamVO) throws BusinessException {
        //初始数据
        ConsultOrderListVO orderListVO = new ConsultOrderListVO();
        //总收入
        Integer totalCost = 0;

        //时间转换
        Date gtTimeDate = DateUtil.parseStrToCustomPatternDate(paramVO.getTime() + "01日00时00分00秒", "yyyy年MM月dd日HH时mm分ss秒");
        String ltTime = DateUtil.formatDate(DateUtil.addMonth(gtTimeDate, 1), DateUtil.DATE_TIME_FORMAT);
        String gtTime = DateUtil.formatDate(gtTimeDate, DateUtil.DATE_TIME_FORMAT);
        LOGGER.info("诊疗收入 ltTime={},gtTime={}", ltTime, gtTime);
        //构建查询sql
        StringBuilder querySql = new StringBuilder();
        querySql.append("SELECT alias.* FROM (SELECT changed_at AS consultTime,inquirer_id AS inquirerId,2 AS costType,1 as freeCost,doctor_id,patient_id,price AS price FROM dr_video_consult")
                .append(" WHERE doctor_id =" + paramVO.getDoctorId() + " AND pay_status=2 AND changed_at > '" + gtTime + "'  AND changed_at < '" + ltTime + "' UNION ALL SELECT cs.end_time AS " +
                                "consultTime," +
                                "inquirer_id AS inquirerId,1 AS costType,cs.cost_type as freeCost,cs.doctor_id,cs.patient_id,cs.cost AS price " +
                                "FROM consult_session cs LEFT JOIN dr_message_consult_order dmco ON cs.session_id=dmco.session_id")
                .append(" WHERE cs.doctor_id=" + paramVO.getDoctorId() + " AND cs.end_time > '" + gtTime + " ' AND cs.end_time < '" + ltTime + "'  AND (dmco.pay_status=2 or cs.cost=0 or cs" +
                                ".cost_type=0) AND cs.end_time is not null) AS alias ORDER BY alias.consultTime DESC");
        //记录数量查询sql
        String countSql = "select count(1) from (" + querySql.toString() + ") t";
        Query countQuery = this.entityManager.createNativeQuery(countSql);
        //总记录数量
        Long totalCount = Long.valueOf(String.valueOf(countQuery.getSingleResult().toString()));
        //查询结果
        Query query = this.entityManager.createNativeQuery(querySql.toString());
        //构建分页数据
        com.naiterui.common.repository.page.Page<ConsultOrderVO> orderVOPage = new com.naiterui.common.repository.page.Page<>();
        orderVOPage.setPageNo(pageParamVO.getPage());
        orderVOPage.setPageSize(pageParamVO.getNum());
        orderVOPage.setTotalCount(totalCount);
        //组合数据
        List<Object> objList = query.getResultList();
        List<ConsultOrderVO> orderVOS = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(objList)){
            List<Long> inquirerIds = new ArrayList<>();
            for (Object obj : objList) {
                Object[] column = (Object[]) obj;
                ConsultOrderVO orderVO = new ConsultOrderVO();
                orderVO.setConsultTime((Date) column[0]);
                orderVO.setInquirerId(((BigInteger) column[1]).longValue());
                orderVO.setCostType(((BigInteger) column[2]).intValue());
                orderVO.setFreeCost(((BigInteger) column[3]).intValue());
                orderVO.setDoctorId(((BigInteger) column[4]).longValue());
                orderVO.setPatientId(((BigInteger) column[5]).longValue());
                if (ConsultSession.COST_TYPE_FREE == orderVO.getFreeCost()) {
                    orderVO.setPrice(0);
                } else {
                    orderVO.setPrice(((Integer) column[6]).intValue());
                }
                orderVOS.add(orderVO);
                inquirerIds.add(((BigInteger) column[1]).longValue());
            }
            //计算总收入
            totalCost = orderVOS.stream().mapToInt(i -> i.getPrice()).sum();

            int start = com.naiterui.common.repository.page.Page.getStartOfPage(orderVOPage.getPageNo(), orderVOPage.getPageSize());
            int end = start + orderVOPage.getPageSize();
            if (orderVOS.size() > start) {
                List<ConsultOrderVO> pageValues = orderVOS.subList(start, end > orderVOS.size() ? orderVOS.size() : end);
                orderVOPage.setResult(pageValues);
                if (orderVOPage != null && CollectionUtil.isNotEmpty(orderVOPage.getResult())) {
                    List<ConsultOrderVO> result = orderVOPage.getResult();
                    List<PatientInquirerBO> inquirers = patientFeignClient.patientInquirerList(inquirerIds);
                    Map<Long, PatientInquirerBO> inquirerMap = inquirers.stream().collect(Collectors.toMap(PatientInquirerBO::getInquirerId, Function.identity()));
                    result.stream().forEach(r -> {
                        r.setGender(Optional.ofNullable(inquirerMap.get(r.getInquirerId()).getGender()).orElse(0));
                        r.setPatientName(Optional.ofNullable(inquirerMap.get(r.getInquirerId()).getName()).orElse("未知"));
                        r.setAge(Optional.ofNullable(inquirerMap.get(r.getInquirerId()).getAge()).orElse("0岁"));
                    });
                }
            }
        }
        orderListVO.setTitle(cn.hutool.core.date.DateUtil.beginOfMonth(gtTimeDate).toString(DateUtil.DATE_FORMAT_IN_COMMA_DATE) + "-" + cn.hutool.core.date.DateUtil.endOfMonth(gtTimeDate).toString(DateUtil.DATE_FORMAT_IN_COMMA_DATE) + " 已结束问诊");
        orderListVO.setTotalPrice(totalCost);
        orderListVO.setOrders(CustomizedPageConvertor.pageConvert(orderVOPage));
        return orderListVO;
    }
}
